package com.chen.demohystriyresttemplate.service.impl;

import com.chen.common.dto.ResponseResult;
import com.chen.demohystriyresttemplate.service.DemoHystriyService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class DemoHystriyServiceImpl {

    @Autowired
    private RestTemplate restTemplate;
    @HystrixCommand(fallbackMethod = "fallback",commandProperties = {
            @HystrixProperty(name = HystrixPropertiesManager.FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS,value = "10")//服务降级:如果并发数达到该设置值，请求会被拒绝和抛出异常并且fallback不会被调用。
    } )
    public ResponseResult test(String name) {
        String url = "http://feign-called/feigncalled/demo1"; //服务名 + 加请求地址
        String request="restTemplate";
        ResponseResult result = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<Object>(request, null), ResponseResult.class).getBody();
        return result;
    }


    /**
     *   熔断方法
     * @param request
     * @return
     */
    private ResponseResult fallback(String request) {
        System.out.println("熔断:"+request);
        //备用逻辑
        return ResponseResult.fail(11).setMessage("熔断了").setMessage("请jiachabug");
    }

}
